package stud.mpgame.network.util;

import org.apache.mina.core.buffer.IoBuffer;

import java.nio.charset.Charset;

/**
 * User: GreK
 * Date: 03.05.11
 * Time: 13:30
 */
public class MessageUtils
{
    public static final Charset UTF8_CHARSET = Charset.availableCharsets().get("UTF-8");

    public static byte[] strToBytes(String str)
    {
        byte[] strBytes = str.getBytes(UTF8_CHARSET);
        int len = strBytes.length;

        byte[] res = new byte[len + 2];
        res[0] = (byte) ((len >>> 8) & 0xff);
        res[1] = (byte) ((len >>> 0) & 0xff);
        System.arraycopy(strBytes, 0, res, 2, len);

        return res;
    }

    public static String bytesToStr(byte[] bytes)
    {
        int len = 0;
        len += (bytes[0] & 0xff) << 8;
        len += (bytes[1] & 0xff) << 0;

        return new String(bytes, 2, len, UTF8_CHARSET);
    }

    public static String bytesToStr(IoBuffer buffer)
    {
        int len = 0;
        len += (buffer.get() & 0xff) << 8;
        len += (buffer.get() & 0xff) << 0;

        String res = new String(buffer.array(), buffer.position(), len, UTF8_CHARSET);
        buffer.position(buffer.position() + len);

        return res;
    }

}
